package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    GeneratePageService generatePageService;
    /**
     * 保存app文章
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        // 1. 封装 article对象
        ApArticle apArticle = dtoToArticle(articleDto);
        // 2. 保存或修改文章
        Long articleId = saveOrUpdateArticle(apArticle);
        // 3. 保存 文章 内容 和 配置 信息
        saveContentAndConfig(articleId,articleDto.getContent());
        //返回文章ID
        generatePageService.generateArticlePage(apArticle.getId());
        return ResponseResult.okResult(apArticle.getId());
    }
    /**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;
    @Value("${file.minio.readPath}")
    private String readPath;
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //参数检查
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer size = dto.getSize();
        if (size==null) {
            size=10;
        }
        dto.setSize(size);
        //如果频道ID为空，那么代表查询全部
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }
        //类型如果不正确，那么默认查询更多
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype)&&!ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询并返回结果
        List<ApArticle> list = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : list) {
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        ResponseResult result = ResponseResult.okResult(list);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据参数加载文章列表  v2
     *
     * @param loadtypeLoadMore
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDto dto, boolean firstPage) {
        if(firstPage){
            String jsonStr = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                if(!hotArticleVoList.isEmpty()&& hotArticleVoList.size() > 0){
                    ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                    responseResult.setHost(webSite);
                    return responseResult;
                }
            }
        }
        return load(loadtypeLoadMore,dto);
    }

    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        //1 查询文档
        if (apArticle==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在");
        }
        // 2. 修改文章 各行为的数量
        apArticle.setViews((int)(apArticle.getViews() + mess.getView()));
        apArticle.setLikes((int)(apArticle.getLikes() + mess.getLike()));
        apArticle.setComment((int)(apArticle.getComment() + mess.getComment()));
        apArticle.setCollection((int)(apArticle.getCollection() + mess.getCollect()));
        updateById(apArticle);
        // 3. 重新计算文章得分
        Integer score = computeScore(apArticle);
        // 4. 判断是否为当日发布的文章，如果是  热度*3
        String publishTime = DateUtils.dateToString(apArticle.getPublishTime());
        String nowTime = DateUtils.dateToString(new Date());
        if (publishTime.equals(nowTime)) {
            score = score * 3;// 今日发布文章  热度 * 3
        }
        // 5. 查询文章对应的频道下的热点文章， 替换分值交低的热点文章
        updateArticleCache(apArticle,score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+apArticle.getChannelId());
        // 6. 查询推荐频道下的热点文章， 替换分值交低的热点文章
        updateArticleCache(apArticle,score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    private void updateArticleCache(ApArticle apArticle, Integer score, String cacheKey) {
        String hotArticle = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(hotArticle)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到热点文章的缓存数据");
        }
        List<HotArticleVo> hotArticleVos = JSONArray.parseArray(hotArticle, HotArticleVo.class);
        boolean isHas = false;
        for (HotArticleVo hotArticleVo : hotArticleVos) {
            if (hotArticleVo.getId().equals(apArticle.getId())) {
                hotArticleVo.setScore(score);
                isHas=true;
                break;
            }
        }
        if (!isHas) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticle);
            hotArticleVo.setScore(score);
            hotArticleVos.add (hotArticleVo);
        }
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 根据权重计算文章得分
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        if (apArticle.getViews() != null) {
            score += apArticle.getViews()* ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    /**
     * 保存文章配置 及 文章内容
     * @param articleId
     * @param content
     */
    private void saveContentAndConfig(Long articleId, String content) {
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true); // 是否允许转发
        apArticleConfig.setIsComment(true);// 是否允许评论
        apArticleConfig.setIsDown(false);// 是否下架
        apArticleConfig.setIsDelete(false);// 是否删除
        apArticleConfig.setArticleId(articleId);// 文章id
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(content);// 文章内容
        apArticleContent.setArticleId(articleId); // 文章id
        apArticleContentMapper.insert(apArticleContent);
    }
    /**
     * 保存文章配置 及 文章内容
     */
    private Long saveOrUpdateArticle(ApArticle apArticle) {

        if (apArticle.getId()==null) {
            //直接保存
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            // 保存
            save(apArticle);  // 返回ID
        }else{
            //删除配置信息
            ApArticle article = getById(apArticle.getId());
            if (apArticle==null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST);
            }
            // 删除之前配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            // 删除之前内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            updateById(apArticle);
        }
        return apArticle.getId();
    }

    private ApArticle dtoToArticle(ArticleDto articleDto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto,apArticle);
        // 根据自媒体用户id 查询 作者id
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, articleDto.getWmUserId()));
        if (apAuthor==null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apArticle.setAuthorId((long) apAuthor.getId());
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }
}
